import requests
import re
import datetime

from bs4 import BeautifulSoup

"""
前期制作文案
机器人流程步骤
步骤1：登入网站后台账号
步骤2：选择“现金系统”---“现金系统”
步骤3：点“锁定”
步骤4：点击出款金额 复制姓名、银行卡号 因为使用民生和招商银行行别回自动识别所以不需要填。
步骤5：在复制金额。
步骤6：到网页页面。把姓名。银行卡号。金额黏贴到银行。
步骤7：点击送出  输入交易密码。完成交易。
步骤8：在到后台点击确定。
注意：如果出现有备注有内容机器人不自动出款让人工处理。
或者出现有手续费的情况。机器人点取消。人工处理
或者出现银行卡信息不符合。机器人无法出款成功。到后台点取消。并且备注是银行卡信息不符合。
机器人就是可以同时开多台机器人进行操作，10个机器人同时抢出款单子，比如机器人1网速比机器人2网速快，那机器人1抢到单子出款，机器人2就等下一个单子，
等于自动判断可以出款的条件。

ckzidong1   密码：qwe123
"""

class wm168(object):
    """docstring for wm168
        通过requests模拟访问wm168网页
        流程如下：
        1.登录https://wm168.wan0002.com/user/login
        2.备注有内容的单子不出
        3.

    """

    session = None

    @classmethod
    def init(self,username,password,otp,baseURI = 'https://wm168.wan0002.com/'):
        #super(wm168, self).__init__()
        self.username = username
        self.password = password
        self.otp = otp
        if self.session is None:
            self.session=requests.Session()#每次访问需要禁用ssh验证
        self.baseURI = baseURI
        self.locked = {}
        print("_初始化",self.baseURI)

    @classmethod
    def login(self):
        "登录"
        self.session.cookies.clear()
        data={'username':self.username,'passwd':self.password,'OTP':self.otp,'lang':'zh-cn'}
        response = self.session.post(self.baseURI+"user/login",data=data,verify=False)
        self.session.headers.update({"Host":self.baseURI.replace("https://","").replace("http://","").replace("/",''),
                                    "Referer":self.baseURI+"agv3/cl/index.php?module=CashWithdrawal"})
        try:
            print(response.content.decode("utf-8"))
        except Exception as e:
            print(response.content)
        print(self.session.cookies)
        print()
        return response.content

    @classmethod
    def catchTicket(self,level=None):
        "爬取页面,获取页面数据"
        if level is None:
            level = []
        self.locked = {}
        print(level)
        level_args = "&".join(["level[]="+_l for _l in level])
        if level_args == 'level[]=':
            level_args = ''
        print(level_args)
        timedelta = datetime.timedelta(hours=4)
        date_start = (datetime.datetime.utcnow() - timedelta).strftime('%Y-%m-%d 00:00:00')
        date_end = (datetime.datetime.utcnow() - timedelta).strftime('%Y-%m-%d 23:59:59')
        headers = {'Referer':self.baseURI+'agv3/cl/index.php?module=CashWithdrawal','Host':self.baseURI.replace("https://","").replace("http://","").replace("/",'')}
        url = self.baseURI+"agv3/cl/index.php?module=CashWithdrawal&hall_id=3820141& \
               retime=0&MaxWithdrawalID=189906168&date_start={date_start}&date_end={date_end}&login_name=&position=1& \
               status[]=0&status[]=1&status[]=2&status[]=3&rows=200&currency=RMB&upperid=alln&fast_bak=&account_id=&amount_min=& \
               amount_max=&_=1501692507&{level_args}".format(date_start=date_start,date_end=date_end,level_args=level_args)
        response = self.session.get(url,verify=False)
        soup = BeautifulSoup(response.content,"lxml")
        result_list = soup.tr.td.table.next_sibling.next
        could_lock = {}
        response_list = [] 
        for i in result_list:
            if i.name == 'form':
                list_id = i.attrs.get("name",'IPL_Form').replace("IPL_Form","")
                child_list = list(i.tr.children)
                shouxufei = child_list[13].div.text.strip()
                if shouxufei != '0':
                    continue
                account_id = child_list[9].div.string
                money = child_list[17].font.string
                _time = child_list[23].div.string
                marker = child_list[29].div.string
                control = child_list[25].div#这里还需要处理
                if '"解锁"' in str(control):
                    self.locked[list_id]={'用户名':account_id,'金额':money,'发起时间':_time,'操作':control}
                elif '"锁定"' in str(control) and marker is None:
                    could_lock[list_id]={'用户名':account_id,'金额':money,'发起时间':_time,'操作':control}
                response_list.append("\t".join([list_id,account_id,money,_time,str(marker),str(control)]))
        response_list.reverse()
        print(response_list,could_lock,self.locked)
        return response_list,could_lock,self.locked

    @classmethod
    def lockTicket(self,wid,message=None):
        """
        锁定, fun=4，wid为出账单id
        请注意：已有其他人锁定中---出现这个即已经在锁定了
        锁定逻辑：
            1.先访问锁定用url进行锁定
            2.二次访问，确定已经被锁定中
            3.爬去页面，确定存在解锁指令
        推荐用message告诉别人这个已经被自动化
        """
        url = self.baseURI+"agv3/cl/index.php?module=WithdrawalStatus&fun=4&wid={wid}&b=1".format(wid=wid)
        try:
            print("尝试锁定",wid)
            response = self.session.get(url,verify=False)
            response = self.session.get(url,verify=False)
            if "已有其他人锁定中" in response.text:
                if self.checkIsLocked(wid):
                    if message != None:
                        self.markTicket(wid,message)
                    print("锁定成功",wid)
                    return True,wid,self.getBankInfo(wid)
        except Exception as e:
            self.unlockTicket(wid,"自动锁定时发生异常")
            raise e

    @classmethod
    def unlockTicket(self,wid,message = None):
        "解锁，fun=0，wid为出账单id"
        if message != None:
            self.markTicket(wid,message)
        url = self.baseURI+"agv3/cl/index.php?module=WithdrawalStatus&fun=0&wid={wid}&b=1".format(wid=wid)
        response = self.session.get(url,verify=False)
        if wid in self.locked:
            self.locked.pop(wid)

    @classmethod
    def submitTicket(self,wid):
        "确定, fun=1，wid为出账单id"
        url = self.baseURI+"agv3/cl/index.php?module=WithdrawalStatus&fun=1&wid={wid}&b=1".format(wid=wid)
        print(url)
        response = self.session.get(url,verify=False)
        print(response.content)
        if wid in self.locked:
            self.locked.pop(wid)
        #TODO

    @classmethod
    def markTicket(self,id,content):
        "备注"
        url = self.baseURI+"agv3/cl/index.php?module=CashWithdrawal&modift=Y&ID={id}&CONTENT={content}".format(id=id,content=content)
        response = self.session.get(url,verify=False)

    @classmethod
    def getBankInfo(self,id):
        "获取银行信息"
        url = self.baseURI+'agv3/cl/index.php?module=CashWithdrawal&action=getWithdrawalData&id={id}'.format(id=id)
        response = self.session.get(url,verify=False)
        return response.json()

    @classmethod   
    def setCookies(self,cookies):
        self.session.cookies.update(cookies)

    @classmethod
    def checkIsLocked(self,wid):
        response = self.catchTicket()
        return (wid in response[2].keys())